<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig?.timeLimit ?? 0 }}MS
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig?.memoryLimit ?? 0 }}B
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig?.stackLimit ?? 0 }}B
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <!-- 新增评论区 -->
          <!-- 评论区 -->
          <a-tab-pane key="comment" :title="computeCount(total)">
            <!-- 回复文章输入框 -->
            <div class="reply-section" v-if="!replyTarget.parentId">
              <a-textarea
                v-model="replyContent"
                placeholder="输入你的评论..."
                :auto-size="{ minRows: 3 }"
              />
              <div class="action-buttons">
                <a-button type="primary" size="small" @click="submitComment"
                  >提交</a-button
                >
                <a-button size="small" @click="cancelReply">取消</a-button>
              </div>
            </div>

            <!-- 评论列表 -->

            <div v-for="comment in comments" :key="comment.id">
              <CommentItem
                :comment="comment"
                @reply="handleReply"
                @like="onLikeChange"
                @cencel="cancelReply"
                @loadComment="loadComments"
              />
            </div>
            <!-- 加载更多按钮 -->
            <div v-if="total > page" class="load-more">
              <a-button type="primary" @click="loadMoreComments"
                >加载更多</a-button
              >
            </div>
          </a-tab-pane>
          <a-tab-pane key="answer" title="答案">
            <div class="kong"></div>
            <MdEditor :value="answer" />
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider :size="0" />
        <a-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交代码
        </a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
  reactive,
  watch,
  withDefaults,
  defineProps,
} from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionSubmitAddRequest,
  // QuestionSubmitControllerService,
  QuestionVO,
} from "../../../generatedQue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import MdEditor from "@/components/MdEditor.vue";
import { IconMessage } from "@arco-design/web-vue/es/icon";
import { CommentControllerService } from "../../../generated/services/CommentControllerService";
import { CommentVO } from "../../../generated/models/CommentVO";
import CommentItem from "@/components/CommentItem.vue";
import { IconHeart, IconHeartFill } from "@arco-design/web-vue/es/icon";
// 原有脚本内容保持不变...

// 新增图标组件注册
const components = {
  IconMessage,
};
const computeCount = (count: number) => {
  if (count > 0 && count < 99) {
    return `评论(${count})`;
  } else if (count >= 99) {
    return "评论(99+)";
  } else {
    return "评论";
  }
};
// 定义各语言对应的代码模板
const languageTemplates: Record<string, string> = {
  java: `public class Main
{
    public static void main(String args[])
    {
        /**
        输入示例：
        int a = Integer.parseInt(args[0]);
        */
    }
}`,
  cpp: `#include <iostream>  
#include <string> // 包含这个头文件以使用 std::stoi  
using namespace std;  

int main(int argc, char* argv[]) {  
    // 转换命令行参数为整数  
    /**
    示例：接收参数
    int nums1 = stoi(argv[1]);  
    int nums2 = stoi(argv[2]);  
    注意，示例答案输入输出有没有换行哦
    */
    return 0;  
}`,
  go: `package main

import "fmt"

func main() {
    // 请在此输入代码
    fmt.Println("Hello, World!")
}`,
  html: `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML Template</title>
</head>
<body>
    <!-- 请在此输入代码 -->
</body>
</html>`,
};

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    "",
    props.id as any
  );
  console.log(res.data);
  question.value = res.data;
};
const addAnswer = async () => {
  console.log("props.id", props.id);
  const res = await QuestionControllerService.getAnswerByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    answer.value = res.data;
  } else {
    message.error("答案加载失败，" + res.message);
  }
};
const onLikeChange = async (comment: CommentVO) => {
  console.log("Comment", comment);
  const res = await CommentControllerService.likeChangeUsingPost("", {
    commentId: comment.id,
  });
  if (res.code === 0) {
    loadComments();
  } else {
    message.error("点赞失败," + res.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: languageTemplates["java"],
});
const answer = ref();
// 添加监听，当 language 改变时更新 code
watch(
  () => form.value.language,
  (newLanguage, oldLanguage) => {
    if (newLanguage !== oldLanguage) {
      form.value.code = languageTemplates[newLanguage];
      console.log("language变化：", newLanguage, "->", oldLanguage);
      console.log("form.value.code变化：", form.value.code);
    }
  }
);

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  const res = await QuestionControllerService.doQuestionSubmitUsingPost("", {
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
  } else {
    message.error("提交失败," + res.message);
  }
};
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  addAnswer();
  loadComments();
});
const page = ref(5);
// 加载更多评论
const loadMoreComments = async () => {
  page.value += 10; // 每次加载 10 条评论
  await loadComments(); // 重新加载评论
};
const total = ref(0);
const loadComments = async () => {
  console.log("props.id", props.id);

  const res = await CommentControllerService.showCommentsUsingPost("", {
    questionId: props.id,
    countlimit: page.value,
  });
  if (res.code === 0) {
    comments.value = res.data.commentsList;
    total.value = res.data.totalCount;
  }
  console.log("res", res);
};
const changeCode = (value: string) => {
  form.value.code = value;
};

// 动态评论数据
const comments = ref<CommentVO[]>([
  {
    id: "1",
    questionId: "",

    user: {
      id: 1,
      userName: "用户A",
      userAvatar: "https://example.com/avatar1.png",
    },
    content: "这道题的解法不错",
    createTime: "1小时前",
    replies: [
      {
        id: "3",
        user: {
          id: 2,
          userName: "用户B",
          userAvatar: "https://example.com/avatar2.png",
        },
        content: "同意，这个方法很有效",
        createTime: "30分钟前",
        replies: [],
      },
    ],
  },
  {
    id: "2",
    questionId: "",
    user: {
      id: 3,
      userName: "用户C",
      userAvatar: "https://example.com/avatar3.png",
    },
    content: "有没有更优的解法？",
    createTime: "45分钟前",
    replies: [],
  },
]);

// 回复相关状态
const replyTarget = reactive({
  parentId: null as string | null,
  rootId: null as string | null,
});
const replyContent = ref("");

// 处理回复点击
const handleReply = (commentId?: string, replyId?: string) => {
  replyTarget.parentId = replyId || commentId || null;
  replyTarget.rootId = replyId ? commentId || null : null;
};

// 提交评论
const submitComment = async () => {
  if (!replyContent.value.trim()) return;
  console.log("replyContent", replyContent.value);
  const res = await CommentControllerService.addCommentUsingPost("", {
    questionId: props.id,
    content: replyContent.value,
  });
  if (res.code === 0) {
    message.success("评论成功");
    loadComments();
  } else {
    message.error("评论失败," + res.message);
  }
  // if (replyTarget.parentId) {
  //   const parentComment = findComment(comments.value, replyTarget.parentId);
  //   if (parentComment) {
  //     // parentComment.replies?.push(newComment);
  //     console.log("parentComment", parentComment);
  //   }
  // } else {
  //   // comments.value.push(newComment);
  // }

  cancelReply();
};

// 查找评论
// const findComment = (
//   comments: CommentVO[],
//   id: string
// ): CommentVO | undefined => {
//   for (const comment of comments) {
//     if (comment.id === id) return comment;
//     if (comment.replies?.length) {
//       const found = findComment(comment.replies, id);
//       if (found) return found;
//     }
//   }
// };

// 取消回复
const cancelReply = () => {
  replyTarget.parentId = null;
  replyTarget.rootId = null;
  replyContent.value = "";
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px !important;
  margin: 0 auto !important;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
#viewQuestionView .kong {
  height: 10px;
}
/* 新增评论区样式 */
.reply-section {
  margin: 16px 0;
  padding-left: 40px;
}

.action-buttons {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action {
  cursor: pointer;
  color: var(--color-text-2);
  transition: color 0.3s;
}

.action:hover {
  color: var(--color-primary);
}
/* 加载更多按钮样式 */
.load-more {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>
